package auto.app.controller;



import auto.app.config.DirectRabbitConfig;
import auto.app.controller.from.PostMail;
import auto.app.controller.from.ResultDetailFrom;
import auto.app.controller.info.ResultInfo;
import auto.app.exetion.MainExection;
import auto.app.model.AutoCollectionResult;
import auto.app.model.AutoFileInfo;
import auto.app.pdf.PdfReportEvent;
import auto.app.pdf.pdfReportVariable;
import auto.app.service.AutoCollectionResultService;
import auto.app.service.AutoFileInfoService;
import auto.app.service.EmailService;
import auto.app.service.ResultService;
import auto.app.util.*;
import auto.app.vo.TestReportVo;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import sun.misc.IOUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static auto.app.exetion.MainExetionMessage.OSSTEMPLATEUPLOADERROR;

/**
 * <p>
 * 测试合集测试结果 前端控制器
 * </p>
 *
 * @author 杨森
 * @since 2022-07-20
 */
@RestController
@RequestMapping("/result")
@Api(value = "测试结果",tags = "测试结果")
@Slf4j
public class ResultController {
    @Autowired
    private ResultService resultService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private AutoCollectionResultService autoCollectionResultService;

    @Autowired
    private AutoFileInfoService autoFileInfoService;

    @Autowired
    private OSSTemplate ossTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;



    @Value("${spring.file.path}")
    private String path;

    @PostMapping(value = "/detail",name = "测试用例查询")
    @ApiOperation(value = "测试用例查询",notes = "用例结果查询")
    public Result<ResultInfo> detail(@Valid @RequestBody ResultDetailFrom resultDetailFrom) throws MainExection {
        ResultInfo detali = resultService.detali(resultDetailFrom);
        return Result.getInstance(ResultInfo.class).setData(detali);
    }
    @GetMapping(value = "/detailCollection/{collectionId}",name = "测试用例查询")
    @ApiOperation(value = "测试用例查询",notes = "用例结果查询")
    public Result<List<ResultInfo>> detailList(@PathVariable Integer collectionId) throws MainExection {
        List<ResultInfo> resultInfos = resultService.detailList(collectionId);
        return Result.getInstanceList(ResultInfo.class).setData(resultInfos);
    }

    @GetMapping(value = "/testreport/{collectionId}",name = "生成测试报告")
    @ApiOperation(value = "生成测试报告",notes = "生成测试报告")
    public void export(@PathVariable Integer collectionId, HttpServletResponse response) throws Exception {
        LambdaQueryWrapper<AutoCollectionResult> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AutoCollectionResult> last = lambdaQueryWrapper.eq(AutoCollectionResult::getCollectionId, collectionId)
                .eq(AutoCollectionResult::getExcuteType,"后台执行")
                .orderByDesc(AutoCollectionResult::getExcuteTime)
                .last("limit 1");
        AutoCollectionResult autoCollectionResultServiceOne = autoCollectionResultService.getOne(last);
        if (ObjectUtil.isNull(autoCollectionResultServiceOne)){
            throw new MainExection(500,"请先执行测试合集");
        }
        LambdaQueryWrapper<AutoFileInfo> autoFileInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AutoFileInfo> autoFileInfoLambdaQueryWrapper1 = autoFileInfoLambdaQueryWrapper.eq(AutoFileInfo::getDataId, autoCollectionResultServiceOne.getId())
                .orderByDesc(AutoFileInfo::getCreateTime)
                .last("limit 1");

        AutoFileInfo autoFileInfoServiceOne = autoFileInfoService.getOne(autoFileInfoLambdaQueryWrapper1);
        String s = ossTemplate.downloadFile(autoFileInfoServiceOne.getFileName());
        if (ObjectUtil.isEmpty(s)){
            throw new MainExection(OSSTEMPLATEUPLOADERROR.getCode(),OSSTEMPLATEUPLOADERROR.getMsg());
        }
        byte[] bytes = FilesUtil.downFileByUrl(s);
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        byteArrayOutputStream.write(bytes);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("测试报告.pdf", "UTF-8"));
        response.setContentType("application/pdf");
        response.setContentLength(byteArrayOutputStream.size());
        ServletOutputStream outputStream = response.getOutputStream();
        //上传OSS文件
        byteArrayOutputStream.writeTo(outputStream);
    }

    @GetMapping(value = "/testreport/excel/{collectionId}",name = "导出测试结果")
    @ApiOperation(value = "导出测试结果",notes = "导出测试结果")
    public void exportExcle(@PathVariable Integer collectionId, HttpServletResponse response) throws Exception {
        List<TestReportVo> testReportVos = resultService.export(collectionId);
       excelUtils.exportExcel("测试报告"+ LocalDateTime.now()+".xls", TestReportVo.class,testReportVos,response,"测试合集执行结果",true);
    }

    @PostMapping(value = "/postmail",name = "发送测试报告")
    @ApiModelProperty(value = "发送测试报告",notes = "发送测试报告")
    public Result<Boolean> postmail(@RequestBody PostMail postMail) throws Exception {
//        邮件发送使用异步mq
        Map<String,Object> map=new HashMap<>();
        map.put("collectionId",postMail.getCollectionId());
        map.put("mailUrlList",postMail.getMailUrlList());
        rabbitTemplate.convertAndSend(DirectRabbitConfig.EXCHANGE_NAME_MAIL, DirectRabbitConfig.ROUTINGKEY_NAME_MAIL, map);
        return Result.getInstance(Boolean.class).setData(true);
    }

    @GetMapping(value = "/testreportnew",name = "pdf版操作手册")
    @ApiOperation(value = "pdf版操作手册",notes = "pdf版操作手册")
    public void export(HttpServletResponse response) throws Exception {
        //准备使用JAVA生成Pdf
        PdfReportEvent report=new PdfReportEvent();
        ByteArrayOutputStream byteArrayOutputStream = report.pdfReportExcult();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("操作手册.pdf", "UTF-8"));
        response.setContentType("application/pdf");
        response.setContentLength(byteArrayOutputStream.size());
        ServletOutputStream outputStream = response.getOutputStream();
        //上传OSS文件
        //String s = ossTemplate.uploadFile("测试报告" + IdUtil.simpleUUID() + ".pdf", new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
        byteArrayOutputStream.writeTo(outputStream);
    }
}

